import json
import os,shutil

# 首先，加载每个模型的第一行图像指标，共35行
# 然后，将每行的第一个数据取出放入列表，共35个，用pair存储（数据值，模型名）
# 再后，将列表中的pair排序。将每个模型的名次保存到一个表中。这个列表可以开36长度，因为最靠后的名次是35【注意，有的是逆序】
# 再后，每个图像的前5名的个数，分别附上权重[21**4,21**3,21**2,21,1]，这样，后面相邻名次有21个才抵得上前面一个，可以有效区分。可以严格按照名次来选。
# 最后，输出该图像最大权值取值的模型名，就可以得到该图像的名次了。

def getAllData():
    dir = "./data"
    filenames = os.listdir(dir)

    get_name = lambda x:x.split('.')[0]     # 获得json文件名

    data = {}
    for file in filenames:
        with open(os.path.join(dir,file), "r", encoding="utf8") as f:
            data[get_name(file)] = json.loads(f.read())
    return data

def extractOneRow(data:dict,row):
    rowData = {}
    for k,v in data.items():
        rowData[k] = v[row]
    return rowData

def extractOneMetrix(rowData:dict,mtx):
    mtxData = []
    for k,v in rowData.items():
        mtxData.append((v[mtx],k))
    return mtxData

def dealOneMetrix(mtxData:[tuple],reverse=False):
    # 可能要逆序排列
    mtxData.sort(key = (lambda x : -x[0]) if not reverse else (lambda x : x[0]))

    weight = [21**4,21**3,21**2,21,1]   #只比较前5个
    wgt = {}
    for index,k in enumerate(mtxData):
        wgt[k[1]] = wgt.get(k[1],0) + weight[index]
        if index == len(weight) - 1: break
    return wgt

def main():
    # mtxs = ['sen','me','mse(small)','avg','std','vifp','snr','min','uqi','qabf','vif','ssim','psnr','ifc','q0i','ce(small)','edge','qcv(small)','sf','qcb']
    # mtxs = ['mse(small)','vifp','snr','min','uqi','qabf','vif','ssim','psnr','ifc','q0i','ce(small)','edge','qcv(small)','sf','qcb']
    # mtxs = ['qcb','vif','qabf','ce(small)','std','qcb','q0i','psnr','vifp','qcv(small)','sen','sf','ifc','min','edge']
    # mtxs = ['qcb','vif','qabf','ce(small)','std','qcb','q0i','psnr','vifp','qcv(small)','sen','sf','ifc']
    mtxs = ['qcb','vif','qabf','ce(small)','std','qcb','q0i','psnr','vifp','qcv(small)','sf','ifc']
    data = getAllData()

    result = {}
    for rId in range(115):
        print("Begin pic No.",rId)
        rowD = extractOneRow(data,rId)
        wgtModel = {}
        for mtx in mtxs:
            mtxD = extractOneMetrix(rowD,mtx)
            print(mtx,end=",")
            wgt = dealOneMetrix(mtxD,mtx in ('mse(small)','ce(small)','qcv(small)'))
            for k,v in wgt.items():
                wgtModel[k] = wgt.get(k) + wgtModel.get(k,0)
        sel = max(wgtModel, key=wgtModel.get)
        print("地面真相选择：",sel)
        if not result.get(sel,None):
            result[sel] = []
        result[sel].append(rId + 1)

    for k,v in result.items():
        print(k,'\t',*v)

if __name__ == '__main__':
    main()